﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Web;
using System.Web.Http;
using System.Net.Http;

using Dxr.Police.Models;
using Dxr.Police.Web.Models;

namespace Dxr.Police.Web.Http.Controllers
{
    public class UploadController : ApiController
    {
        public Options.CommonElement Option
        { get; set; }

        [HttpPost]
        public Dxr.Police.Models.HttpResult File()
        {
            var provider = new MultipartFormDataProvider();

            Request.Content.ReadAsMultipartAsync(provider).Wait();

            var model = new FileModel()
            {
                id = provider.FormData["id"],
                name = provider.FormData["name"],
                type = provider.FormData["type"],
                lastModifiedDate = provider.FormData["lastModifiedDate"],
                size = provider.FormData["size"],
            };

            if (provider.FileContents.Count < 1)
                return new HttpResult
                {
                    ret = HttpResult.Error,
                    msg = "上传失败",
                    content = model.id
                };

            var date = DateTime.Now.ToString("yyyyMMdd");
            var localPath = Path.Combine(string.IsNullOrEmpty(Option.RootPath) ? AppDomain.CurrentDomain.BaseDirectory : Option.RootPath, "upload", date);

            if (!Directory.Exists(localPath))
                Directory.CreateDirectory(localPath);

            var filename = Guid.NewGuid().ToString() + Path.GetExtension(model.name);

            var fileContent = provider.FileContents[0];

            using (var stream = fileContent.ReadAsStreamAsync().Result)
            {
                using (StreamWriter sw = new StreamWriter(Path.Combine(localPath, filename)))
                {
                    stream.CopyTo(sw.BaseStream);
                    sw.Flush();
                }
            }

            return new HttpResult
            {
                ret = HttpResult.Success,
                content = new
                {
                    model.id,
                    model.name,
                    url = $"/upload/{date}/{filename}",
                    path = Path.Combine(localPath, filename),
                }
            };
        }

        public class FileModel
        {
            public string id
            { get; set; }
            public string name
            { get; set; }
            public string type
            { get; set; }
            public string lastModifiedDate
            { get; set; }
            public string size
            { get; set; }
        }
    }
}
